<template>
  <div class="inspection-task-container">
    <el-card>
      <div slot="header" class="card-header">
        <span>巡检任务管理</span>
      </div>
      <div class="search-container">

        <el-select v-model="searchForm.status" placeholder="任务状态" style="width: 150px; margin-right: 10px;">
          <el-option label="全部" value=""></el-option>
          <el-option label="待执行" value="1"></el-option>
          <el-option label="执行中" value="2"></el-option>
          <el-option label="已完成" value="3"></el-option>
          <el-option label="已逾期" value="4"></el-option>
        </el-select>
        <el-button type="primary" @click="handle_search">搜索</el-button>
          <el-button @click="handle_reset">重置</el-button>
        <el-button type="success" @click="handle_add">新增任务</el-button>
      </div>
      
      <el-table :data="taskList" style="width: 100%;">
        <el-table-column prop="id" label="任务ID"></el-table-column>
        <el-table-column prop="taskName" label="任务名称"></el-table-column>
        <el-table-column prop="deviceName" label="巡检设备"></el-table-column>
        <el-table-column prop="assigneeName" label="负责人"></el-table-column>
        <el-table-column prop="startTime" label="开始时间"></el-table-column>
    <el-table-column prop="endTime" label="结束时间"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag :type="statusMap[scope.row.status]">{{ statusText[scope.row.status] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="taskType" label="任务类型">
          <template slot-scope="scope">
            <el-tag size="small" v-if="scope.row.taskType === 1" type="primary">计划任务</el-tag>
            <el-tag size="small" v-else-if="scope.row.taskType === 2" type="warning">临时任务</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button size="small" @click="handle_edit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handle_delete(scope.row)">删除</el-button>
            <el-button size="small" type="primary" @click="handle_view(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, jumper, ->, total"
          :total="total"
          :page-size="page_size"
          :current-page="page_num"
          @current-change="handle_current_change"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 新增/编辑任务对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialog_visible"
      width="600px"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model.trim="form.taskName" placeholder="请输入任务名称"></el-input>
        </el-form-item>
        <el-form-item label="巡检计划" prop="planId">
          <el-select v-model="form.planId" placeholder="请选择巡检计划">
            <el-option label="月度巡检计划" :value="1"></el-option>
            <el-option label="季度巡检计划" :value="2"></el-option>
            <el-option label="年度巡检计划" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="巡检设备" prop="deviceId">
          <el-select v-model="form.deviceId" placeholder="请选择巡检设备">
            <el-option v-for="device in deviceList" :key="device.id" :label="device.deviceName" :value="device.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="assigneeId">
          <el-select v-model="form.assigneeId" placeholder="请选择负责人">
            <el-option v-for="user in inspectorList" :key="user.id" :label="user.username" :value="user.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="form.startTime" type="datetime" placeholder="请选择开始时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="form.endTime" type="datetime" placeholder="请选择结束时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="任务描述">
          <el-input v-model.trim="form.description" type="textarea" placeholder="请输入任务描述"></el-input>
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <el-radio-group v-model="form.taskType">
            <el-radio label="1">计划任务</el-radio>
            <el-radio label="2">临时任务</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialog_visible = false">取消</el-button>
        <el-button type="primary" @click="handle_submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import inspectionTaskApi from '@/api/inspection-task'
import deviceApi from '@/api/device'
import userApi from '@/api/sys-user'
  export default {
    name: 'InspectionTask',
    data() {
    return {
      searchForm: {
        taskName: '',
        status: ''
      },
      taskList: [],
      total: 0,
      page_num: 1,
      page_size: 10,
      dialog_visible: false,
      dialogTitle: '新增任务',
      form: {
        id: '',
        taskName: '',
        planId: '',
        deviceId: '',
        assigneeId: '',
        startTime: '',
        endTime: '',
        description: '',
        taskType: 1
      },
      deviceList: [],
      inspectorList: [],
      rules: {
        taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        planId: [{ required: true, message: '请选择巡检计划', trigger: 'change' }],
        deviceId: [{ required: true, message: '请选择巡检设备', trigger: 'change' }],
        assigneeId: [{ required: true, message: '请选择负责人', trigger: 'change' }],
        startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
      },
      statusMap: {
        1: 'warning',
        2: 'primary',
        3: 'success',
        4: 'danger'
      },
      statusText: {
        1: '待执行',
        2: '执行中',
        3: '已完成',
        4: '已逾期'
      }
    }
  },
  created() {
      this.get_device_list()
    this.get_inspector_list()
    this.get_task_list()

  },
  methods: {
    get_task_list() {
      inspectionTaskApi.list({
        taskName: this.searchForm.taskName,
        status: this.searchForm.status === '' ? null : this.searchForm.status,
        page_num: this.page_num,
        page_size: this.page_size
      }).then(res => {
        console.log(res,"获取任务列表成功");
        
        // 安全地访问数据结构
        if (res && res.data) {
          let records = res.data.records || []
          // 根据deviceId匹配设备名称
          records = records.map(task => {
            // 查找对应的设备
            const device = this.deviceList.find(d => d.id === task.deviceId)
            const inspector = this.inspectorList.find(u => u.id === task.assigneeId)
            // 添加设备名称字段
            return {
              ...task,
              deviceName: device ? device.deviceName : '未知设备',
              assigneeName: inspector ? inspector.username : '未知负责人'
            }
          })
          this.taskList = records
          this.total = res.data.total || 0
        } else {
          // 如果数据结构不符合预期，使用默认值
          this.taskList = []
          this.total = 0
          console.warn('API返回的数据结构不符合预期')
        }
      }).catch(error => {
        console.error('获取任务列表失败:', error)
        this.taskList = []
        this.total = 0
        this.$message.error('获取任务列表失败，请稍后重试')
      })
    },
    get_device_list() {
      // 调用API获取设备列表
      deviceApi.list().then(res => {
        if (res && res.data) {
          // 处理可能是分页数据或直接数组的情况
          const data = Array.isArray(res.data) ? res.data : (res.data.records || [])
          this.deviceList = data.map(item => ({
            id: item.id,
            deviceName: item.deviceName || item.name
          }))
        } else {
          this.deviceList = []
        }
      }).catch(error => {
        this.deviceList = []
        this.$message.error('获取设备列表失败：' + (error.message || '未知错误'))
        console.error('获取设备列表失败:', error)
      })
    },
    get_inspector_list() {
      // 调用API获取用户列表作为巡检人员
      userApi.list().then(res => {
        if (res && res.data) {
          // 处理可能是分页数据或直接数组的情况
          const data = Array.isArray(res.data) ? res.data : (res.data.records || [])
          this.inspectorList = data.map(item => ({
            id: item.id,
            username: item.username || item.name
          }))
        } else {
          this.inspectorList = []
        }
      }).catch(error => {
        this.inspectorList = []
        this.$message.error('获取巡检人员列表失败：' + (error.message || '未知错误'))
        console.error('获取巡检人员列表失败:', error)
      })
    },
    handle_search() {
      // 搜索逻辑
      this.page_num = 1
      this.get_task_list()
    },
    handle_reset() {
      // 重置搜索条件
      this.searchForm = {
        taskName: '',
        status: ''
      }
      this.get_task_list()
    },
    handle_reset() {
      // 重置搜索条件
      this.searchForm = {
        taskName: '',
        status: ''
      }
      this.get_task_list()
    },
    handle_add() {
      // 新增任务
      this.dialogTitle = '新增任务'
      this.form = {
          id: '',
          taskName: '',
          planId: '',
          deviceId: '',
          assigneeId: '',
          startTime: '',
          endTime: '',
          description: '',
          taskType: 1
        }
      this.dialog_visible = true
    },
    handle_edit(row) {
      // 编辑任务
      this.dialogTitle = '编辑任务'
      this.form = { ...row }
      this.dialog_visible = true
    },
    handle_delete(row) {
      // 删除任务
      this.$confirm(`确定要删除任务「${row.taskName}」吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 执行删除操作
        inspectionTaskApi.delete(row.id).then(res => {
          this.$message.success('删除成功')
          this.get_task_list()
        }).catch(error => {
          console.error('删除任务失败:', error)
          this.$message.error('删除失败，请稍后重试')
        })
      }).catch(() => {})
    },
    handle_view(row) {
      // 查看任务详情
      this.$router.push(`/inspection/task/detail/${row.id}`)
    },
    handle_submit() {
      // 提交表单
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 确保时间格式正确和添加时间戳
          const form_data = {
            ...this.form,
            updatedAt: new Date()
          }
          if (!form_data.id) {
            form_data.createdAt = new Date()
          }
          // 执行保存操作
          const api = form_data.id ? inspectionTaskApi.update : inspectionTaskApi.add
          api(form_data).then(res => {
            this.$message.success('保存成功')
            this.dialog_visible = false
            this.get_task_list()
          }).catch(error => {
            this.$message.error('保存失败：' + (error.message || '未知错误'))
            console.error('保存巡检任务失败:', error)
          })
        }
      })
    },
    handle_current_change(val) {
      // 分页切换
      this.page_num = val
      this.get_task_list()
    }
  }
}
</script>

<style scoped>
.inspection-task-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>